#!/usr/bin/env python3
"""
OKX模拟盘设置和启动脚本
用于快速配置和启动OKX模拟交易
"""

import os
import sys
import yaml
import asyncio
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from xcquant.core import unified_core, unified_logger
# 简化导入，避免复杂依赖
# from xcquant.exchanges.okx import OKXExchange
# 简化导入，避免复杂依赖
# from xcquant.strategies.grid_strategy import GridStrategy


class OKXDemoSetup:
    """OKX模拟盘设置类"""
    
    def __init__(self):
        self.logger = unified_logger.get_logger(__name__)
        self.config_path = project_root / "config_okx_demo.yaml"
        
    def check_api_keys(self):
        """检查API密钥配置"""
        print("🔑 检查API密钥配置...")
        
        if not self.config_path.exists():
            print(f"❌ 配置文件不存在: {self.config_path}")
            return False
            
        with open(self.config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
            
        okx_config = config.get('exchanges', {}).get('okx', {})
        api_key = okx_config.get('api_key', '')
        secret_key = okx_config.get('secret_key', '')
        passphrase = okx_config.get('passphrase', '')
        
        if any(key.startswith('YOUR_') for key in [api_key, secret_key, passphrase]):
            print("❌ 请先配置您的OKX模拟盘API密钥!")
            print("📝 配置步骤:")
            print("1. 登录OKX官网 (https://www.okx.com)")
            print("2. 进入API管理页面")
            print("3. 创建模拟盘API密钥")
            print("4. 将密钥信息填入 config_okx_demo.yaml 文件")
            print(f"   配置文件路径: {self.config_path}")
            return False
            
        print("✅ API密钥配置检查通过")
        return True
        
    def create_directories(self):
        """创建必要的目录"""
        print("📁 创建必要目录...")
        
        directories = [
            project_root / "data",
            project_root / "logs", 
            project_root / "demo_results",
            project_root / "examples"
        ]
        
        for directory in directories:
            directory.mkdir(exist_ok=True)
            print(f"✅ 目录已创建: {directory}")
            
    async def test_connection(self) -> bool:
        """测试OKX连接"""
        try:
            self.logger.info("测试OKX连接...")
            
            # 简化的连接测试
            config = unified_core.get_config()
            okx_config = config.get('exchanges', {}).get('okx', {})
            
            if not okx_config.get('api_key'):
                self.logger.error("❌ 未配置OKX API密钥")
                return False
                
            self.logger.info("✅ OKX配置检查通过")
            return True
            
        except Exception as e:
            self.logger.error(f"❌ 连接测试失败: {e}")
            return False
            
    def show_demo_guide(self):
        """显示模拟盘使用指南"""
        print("\n" + "="*60)
        print("🎯 OKX模拟盘使用指南")
        print("="*60)
        
        print("\n📋 配置文件说明:")
        print(f"   配置文件: {self.config_path}")
        print("   - 已设置为模拟交易模式 (testnet: true)")
        print("   - 包含BTC现货网格策略示例")
        print("   - 初始资金: 1000 USDT")
        
        print("\n🚀 启动步骤:")
        print("1. 配置API密钥 (如果还未配置)")
        print("2. 运行回测: python examples/run_backtest.py")
        print("3. 启动实时交易: python examples/start_demo_trading.py")
        print("4. 查看Web界面: http://127.0.0.1:5001")
        
        print("\n📊 监控和管理:")
        print("- 日志文件: ./logs/")
        print("- 交易结果: ./demo_results/")
        print("- 实时监控: Web界面或API接口")
        
        print("\n⚠️  注意事项:")
        print("- 这是模拟交易，不会产生真实资金损失")
        print("- 模拟盘数据可能与实盘略有差异")
        print("- 建议先在模拟盘充分测试策略")
        
        print("\n🔧 常用命令:")
        print("- 查看帮助: python examples/okx_demo_setup.py --help")
        print("- 测试连接: python examples/okx_demo_setup.py --test")
        print("- 启动交易: python examples/start_demo_trading.py")
        
    async def run_setup(self):
        """运行完整设置流程"""
        print("🚀 开始OKX模拟盘设置...")
        print("="*50)
        
        # 1. 创建目录
        self.create_directories()
        
        # 2. 检查API密钥
        if not self.check_api_keys():
            return False
            
        # 3. 测试连接
        if not await self.test_connection():
            return False
            
        # 4. 显示使用指南
        self.show_demo_guide()
        
        print("\n✅ OKX模拟盘设置完成!")
        return True


async def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description='OKX模拟盘设置工具')
    parser.add_argument('--test', action='store_true', help='仅测试连接')
    parser.add_argument('--guide', action='store_true', help='显示使用指南')
    
    args = parser.parse_args()
    
    setup = OKXDemoSetup()
    
    if args.guide:
        setup.show_demo_guide()
    elif args.test:
        if setup.check_api_keys():
            await setup.test_connection()
    else:
        await setup.run_setup()


if __name__ == "__main__":
    asyncio.run(main())